package com.wxy.demo;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

/**
 * <p>
 * 发布
 * </p>
 *
 * @author e-Xiaoyuan.Wang
 * @since 2022/7/25 15:53
 */
public class PublishDemo {
    public static void main(String[] args) {
        String topic = "test";
        String content = "hello 哈哈";
        int qos = 1;
        String broker = "tcp://127.0.0.1:1883";
        String userName = "admin";
        String password = "test";
        String clientId = "pubClient";
        try {
            // 创建客户端
            MqttClient mqttClient = new MqttClient(broker, clientId, new MemoryPersistence());
            // 创建链接参数
            MqttConnectOptions connOpts = new MqttConnectOptions();
            // 在重新启动和重新连接时记住状态
            connOpts.setCleanSession(false);
            // 设置连接的用户名
            connOpts.setUserName(userName);
            connOpts.setPassword(password.toCharArray());
            // 建立连接
            mqttClient.connect(connOpts);
            // 创建消息
            MqttMessage message = new MqttMessage(content.getBytes());
            // 设置消息的服务质量
            message.setQos(qos);
            // 发布消息
            for (int i = 0; i < 10; i++) {
                mqttClient.publish(topic, message);
                System.out.println("发布消息：topic = " + topic + "，message = " + message);
            }
            // 断开连接
            mqttClient.disconnect();
            // 关闭客户端
            mqttClient.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
